package com.sharp.framework.aop.db;

import com.sharp.kernel.config.db.DataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * Title: DynamicDataSourceAspect
 * Description: Copyright: Copyright (c) 2019 Company: BHFAE
 *
 * @author Sharp
 * @date 2022/6/6 14:45
 */
@Slf4j
@Aspect
@Component
public class DynamicDataSourceAspect {

    private static final String BASE_PACKAGE_NAME = "com.sharp.";
    private static final String BASE_DAO_PACKAGE_NAME = "dao";
    private static final String PACKAGE_SEP = ".";

    @Pointcut("execution(public * com.sharp.framework.*Repository.*(..))")
    public void baseRepository() {
        // Just a pointCut function
    }

    @Pointcut("execution(public * com.sharp..dao..repository..*.*(..))")
    public void repository() {
        // Just a pointCut function
    }

    @Before("baseRepository() ||repository()")
    public void before(JoinPoint point) {
        String targetPackageName = point.getTarget().getClass().getPackage().getName();
        String temp = targetPackageName.substring(BASE_PACKAGE_NAME.length());
        int daoIndex = temp.indexOf(BASE_DAO_PACKAGE_NAME);
        if (daoIndex <= 0) {
            return;
        }
        temp = temp.substring(0, daoIndex - 1);
        int endIndex = (temp.contains(PACKAGE_SEP)) ? temp.indexOf(PACKAGE_SEP) : temp.length();
        String targetDbName = temp.substring(0, endIndex);
        DataSourceContextHolder.setDB(targetDbName);
    }

    @After("baseRepository() ||repository()")
    public void after() {
        DataSourceContextHolder.clearDB();
    }
}
